package com.ccl.iot.asynctask;


import android.content.Context;
import android.util.Log;

import com.ccl.iot.bean.CodeviewBean;
import com.ccl.iot.device.IOTSubBLir;
import com.ccl.iot.ir.BlirConst;
import com.ccl.iot.ir.DBUtils;
import com.ccl.iot.publics.Messager;
import com.kookong.app.data.IrData;
import com.mysql.jdbc.Connection;

import java.sql.SQLException;
import java.util.ArrayList;

public class SaveAllIrTask extends CustomTask<ArrayList<IrData.IrKey>, Void, Long> {

    private IOTSubBLir mSubBLir;

    public SaveAllIrTask(Context context, IOTSubBLir subBLir) {
        super(context, "保存中...");
        mSubBLir = subBLir;
    }

    @Override
    protected Long doInBackground(ArrayList<IrData.IrKey>... params) {
        long fixed = 0;
        Connection dbConn = DBUtils.getDBConn();
        if (dbConn != null) {
            int subId;
            if (mSubBLir.isTmp()) {
                subId = (int) DBUtils.getSubDevVer(mSubBLir.getDbId(), dbConn);
//                mSubBLir.setName(subId, mSubBLir.getName());
                mSubBLir.setName(mSubBLir.getName());
            } else {
                subId = (int) mSubBLir.getSubId();
            }

            Log.e("SubId", "SubId: " + subId);

            ArrayList<IrData.IrKey> irDatas = params[0];

            if (irDatas != null && irDatas.size() > 0)
                for (IrData.IrKey key : irDatas) {
                    String ir = BlirConst.kk2bl(key.pulse);
                    fixed = DBUtils.addIrCode(mSubBLir.getDbId(), subId, mSubBLir.getDevType(), key.fkey, key.fname, DBUtils.CODE_TYPE_FIXED, ir, dbConn);
                    if (fixed != 0) {
                        CodeviewBean bean = new CodeviewBean(mSubBLir.getDbId(), subId, mSubBLir.getDevType(), key.fkey, key.fname, DBUtils.CODE_TYPE_FIXED, ir, fixed);
                        mSubBLir.getSuperDev().addIrCode(bean);
                    }
                }

            try {
                dbConn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return fixed;
    }

    @Override
    protected void onPostExecute(Long result) {
        super.onPostExecute(result);
        if (result != 0) {
            Messager.Show("保存成功");
        } else {
            Messager.Show("保存失败");
        }
    }
}
